﻿using System;
using System.Collections.ObjectModel;
using System.ComponentModel.Composition;
using System.Net;
using System.Xml.Serialization;
using FinMkts.CFD.Rest;
using Microsoft.Practices.Composite.Events;

namespace FinMkts.CFD.DataService
{
    [Export(typeof(IInstrumentService))]
    public class InstrumentService : IInstrumentService
    {
        private readonly IEventAggregator _eventAggregator;

        [ImportingConstructor]
        public InstrumentService(IEventAggregator eventAggregator)
        {
            _eventAggregator = eventAggregator;
        }

        public void GetAll()
        {
            var webRequest = WebRequest.Create("http://localhost/FinMkts.CFD.Rest/Instruments") as HttpWebRequest;
            if (webRequest != null)
                webRequest.BeginGetResponse(GetAllResult, webRequest);
        }

        private void GetAllResult(IAsyncResult ar)
        {
            var webRequest = ar.AsyncState as HttpWebRequest;
            if (webRequest == null) return;

            WebResponse webResponse = webRequest.EndGetResponse(ar);

            var s = new XmlSerializer(typeof(ObservableCollection<InstrumentDC>));
            var instruments = (ObservableCollection<InstrumentDC>)s.Deserialize(webResponse.GetResponseStream());

            _eventAggregator.GetEvent<InstrumentsReceivedEvent>().Publish(new InstrumentEventArgs(instruments));
        }
    }
}
